package com.coocaa.x.framework.app;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.coocaa.x.framework.R;
import com.coocaa.x.framework.data.JObject;
import com.coocaa.x.framework.utils.LiteHandlerThread;

import java.net.URI;

/**
 * Created by lu on 15-11-24.
 */
public abstract class SplashDialog extends Dialog {
    public static class SplashDialogData extends JObject {
        public String url; //图片链接
        public int duration; //单位：秒
        public String extra; //扩展参数
//        public boolean downloaded;
    }

    private SharedPreferences sp = null;
    protected Context mContext = null;
    private String key;
    private FrameLayout root;
    private boolean bUseCache = false;
    private boolean bCreated = false;


    private boolean bCalledLoadData = false;
    private SplashDialogData data = null;

    public SplashDialog(Context context, String key) {
        super(context, R.style.Dialog_Fullscreen);
        mContext = context;
        this.key = key;
        root = new FrameLayout(mContext);
        root.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        sp = mContext.getSharedPreferences("splash", Context.MODE_WORLD_READABLE
                + Context.MODE_WORLD_WRITEABLE);
    }

    protected abstract SplashDialogData getOnlineData() throws Exception;

    protected abstract void performDownloadData(SplashDialogData data);

    protected abstract View createContentView(SplashDialogData data);

    protected final void setBackgroud(int resID) {
        Drawable drawable = root.getBackground();
        if (drawable != null) {
            drawable.setCallback(null);
        }
        root.setBackgroundDrawable(mContext.getResources().getDrawable(resID));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bUseCache = hasCache();
        View view = createContentView(data);
        if (view == null)
            dismiss();
        else {
            root.removeAllViews();
            root.addView(view);
            setContentView(root);
            LiteHandlerThread.postDelayedOnUiThread(new Runnable() {
                @Override
                public void run() {
                    SplashDialog.this.dismiss();
                }
            }, getDuration());
        }
        synchronized (this) {
            bCreated = true;
            notify();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            return true;
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void show() {
        bCreated = false;
        super.show();
    }

    protected int getDuration() {
//        if (data != null) {
//            try {
//                URI.create(data.url);
//                return data.duration * 1000;
//            } catch (Exception e) {
//                return 3000;
//            }
//        }
        return 3000;
    }

    protected synchronized boolean hasCache() {
        data = loadCache(SplashDialogData.class);
        if (data != null && data.url == null) {
            data = null;
        }
        if (!bCalledLoadData) {
            bCalledLoadData = true;
            CoocaaApplication.post(new Runnable() {

                @Override
                public void run() {
                    SplashDialogData newCache;
                    try {
                        newCache = getOnlineData();
                    } catch (Exception e) {
                        e.printStackTrace();
                        clearCache();
                        bCalledLoadData = false;
                        return;
                    }
                    saveCache(newCache);
//                    boolean toDownloadwCache = false;
//                    SplashDialogData _cache = loadCache(SplashDialogData.class);
//                    if (_cache == null && newCache != null) {
//                        _cache = newCache;
//                        _cache.downloaded = false;
//                        saveCache(_cache);
//                        toDownloadwCache = true;
//                    } else if (_cache != null && newCache != null) {
//                        if (_cache.url == null || !_cache.url.equals(newCache.url)) {
//                            _cache = newCache;
//                            _cache.downloaded = false;
//                            saveCache(_cache);
//                            toDownloadwCache = true;
//                        } else {
//                            if (!_cache.downloaded)
//                                toDownloadwCache = true;
//                        }
//                    }
//                    if (toDownloadwCache)
//                        performDownloadData(newCache);
                    bCalledLoadData = false;
                }
            });
        }
        if (data == null)// || !data.downloaded)
            return false;
        return true;
    }

    protected final ViewGroup getContentView() {
        return root;
    }

    public final boolean useCache() {
        LiteHandlerThread.checkMainThread();
        synchronized (this) {
            if (!bCreated)
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
        return bUseCache;
    }

    protected final void saveCache(JObject obj) {
        synchronized (sp) {
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(key, obj.toJSONString());
            editor.commit();
        }
    }

    protected final <T> T loadCache(Class<T> clazz) {
        synchronized (sp) {
            try {
                String value = sp.getString(key, "");
                return JObject.parseJObject(value, clazz);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    protected final void clearCache() {
        synchronized (sp) {
            sp.edit().remove(key).commit();
        }
    }
}
